import os
import cv2
import sys
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5 import QtMultimedia
from moviepy.editor import *
from moviepy.audio.fx.volumex import volumex
"""
剪辑窗口，可以剪辑视频与音频
"""

class Myslider(QSlider):

    def __init__(self, director):
        super(Myslider, self).__init__()
        # self.setLayoutDirection(director)
        # self.setMinimumHeight(50)
        self.setOrientation(director)
        self.setMinimum(0)
        self.setSingleStep(1)

    def mousePressEvent(self, QMouseEvent):
        x = QMouseEvent.pos().x()
        per = x * 1.0 / self.width()
        value = per * (self.maximum() - self.minimum()) + self.minimum()
        self.setValue(int(value))

        super(Myslider, self).mousePressEvent(QMouseEvent)

class AudioItem(QGraphicsItem):
    def __init__(self,player,data,width,height):
        super(AudioItem, self).__init__()
        self.player=player
        self.data=data
        self.end=data['end'] if 'end' in data.keys() else None
        self.width=width*self.data['scale']
        self.height=height
        self.status ='stop'  #初始状态stop  self.data['status']
        self.hold=-1  #是否暂停状态-1为否，1则为暂停状态，当-1时继续播放
        self.rect=QRectF(0,0,width,height)
        self.setAcceptDrops(True)
        self.setFlag(QGraphicsItem.ItemIsSelectable, True)
        self.setFlag(QGraphicsItem.ItemIsMovable, True)



    def boundingRect(self):
        # if self.customLength > 0:
        #     self.width=self.customLength*self.ui_width#
        # return QRectF(0, 0, (self.width / self.scale()) - 20, self.height / self.scale())
        return self.rect

    def paint(self, QPainter, QStyleOptionGraphicsItem, widget=None):
        # 选中状态变色
        pen = QPen()
        if self.isSelected():
            # print('SSS')
            pen.setColor(QColor('#B0C4DE'))
            pen.setWidth(2)
        font = QFont('', 15)
        QPainter.setPen(pen)

        QPainter.setFont(font)
        QPainter.setBrush(QBrush(QColor('#FFA500')))

        QPainter.drawRoundedRect(self.rect,25,25)
        QPainter.drawText(self.rect, Qt.AlignCenter, self.data['name'])

        status_img='stop.png'
        if self.status=='stop':
            status_img='stop.png'
        elif self.status=='play':
            status_img = 'play.png'
        elif self.status=='pause':
            status_img = 'pause.png'
        status_map_path = os.path.join(os.path.dirname(os.path.dirname(__file__)),'imgs',status_img)
        status_map = QPixmap(status_map_path)

        QPainter.drawPixmap(QPointF(8, 8), status_map)
        # QPainter.drawPixmap(self.rect, Qt.AlignLeft, status_map)



    def dragEnterEvent(self, QGraphicsSceneDragDropEvent):
        QGraphicsSceneDragDropEvent.setAccepted(True)

    def mousePressEvent(self, QGraphicsSceneMouseEvent):
        print('点我了',self.data)
        print(self.hold,self.status)

        # url = QUrl.fromLocalFile(self.data['path'])
        # content = QtMultimedia.QMediaContent(url)
        # self.player = QtMultimedia.QMediaPlayer()
        # self.player.setMedia(content)

        clip_duration=0
        if not self.end:
            duration=self.player.duration()
            print('duration:',duration)
            self.data['duration']=int(duration/1000)
            clip_duration=self.data['duration']
        else:
            clip_duration=self.end-self.data['start']+1
        view = self.scene().views()[0]
        view.reset_parent_slider(self.data['start'],clip_duration)
        view.reset_parent_btn(self.hold,self.status)  #更新当前暂停按钮状态
        super(AudioItem, self).mousePressEvent(QGraphicsSceneMouseEvent)

    def play(self,start):
        self.player.setPosition(start*1000)
        self.player.play()
        self.status='play'
        self.update()

    def pause(self):
        if self.hold==-1:  #没有暂停
            self.player.pause()
            self.status = 'pause'
            self.hold*=-1
            self.update()
        else:  #本身是暂停状态
            self.player.play()
            self.status = 'play'
            self.hold*=-1
            self.update()

    def stop(self):
        self.player.stop()
        self.status = 'stop'
        self.update()


class VideoItem(QGraphicsItem):
    def __init__(self,data,width,height):
        super(VideoItem, self).__init__()
        # self.player=player
        self.data=data
        self.width=width*self.data['scale']
        self.height=height
        self.rect=QRectF(0,0,width,height)
        self.setAcceptDrops(True)
        self.setFlag(QGraphicsItem.ItemIsSelectable, True)
        self.setFlag(QGraphicsItem.ItemIsMovable, True)


    def boundingRect(self):
        # if self.customLength > 0:
        #     self.width=self.customLength*self.ui_width#
        # return QRectF(0, 0, (self.width / self.scale()) - 20, self.height / self.scale())
        return self.rect

    def paint(self, QPainter, QStyleOptionGraphicsItem, widget=None):
        # 选中状态变色
        pen = QPen()
        if self.isSelected():
            # print('SSS')
            pen.setColor(QColor('#B0C4DE'))
            pen.setWidth(2)
        font = QFont('', 15)
        QPainter.setPen(pen)
        QPainter.setFont(font)
        QPainter.setBrush(QBrush(QColor('#9370DB')))
        QPainter.drawRoundedRect(self.rect,25,25)
        QPainter.drawText(self.rect, Qt.AlignCenter, self.data['name'])
        # img=QPixmap(self.img_path)
        # QPainter.drawPixmap(0, 0, self.rect.width(), self.rect.height(), img)
        # QPainter.drawPixmap(0, 0, self.width, self.height, img)
        # QPainter.drawText(self.rect, Qt.AlignCenter, self.deep)

    # def set_imgpath(self,imgpath):
    #     self.img_path=imgpath
    #     self.update()

    def dragEnterEvent(self, QGraphicsSceneDragDropEvent):
        QGraphicsSceneDragDropEvent.setAccepted(True)

    def mousePressEvent(self, QGraphicsSceneMouseEvent):
        print('点我了')
        super(VideoItem, self).mousePressEvent(QGraphicsSceneMouseEvent)

    # def play(self,start):
    #     self.player.setPosition(start*1000)
    #     self.player.play()
    #
    # def pause(self):
    #     self.player.pause()
    #
    # def stop(self):
    #     self.player.stop()


class ClipGraphicView(QGraphicsView):
    """
    剪辑视图
    """
    def __init__(self,parent=None):
        super(ClipGraphicView, self).__init__(parent)
        self.parent=parent

        self.setDragMode(QGraphicsView.RubberBandDrag)

        # self.setStyleSheet("padding:0px;border:0px")
        self.setStyleSheet('GraphicView{background-color:#DCDCDC}'
                           'QScrollBar{width:1px}')
        self.setRenderHint(QPainter.Antialiasing)
        self.setRenderHint(QPainter.TextAntialiasing)
        self.setViewportUpdateMode(QGraphicsView.FullViewportUpdate)  # 全视图，可以消除残影
        self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
        self.setMouseTracking(1)
        self.setAcceptDrops(True)
        self.scene=QGraphicsScene()
        self.setScene(self.scene)
        self.scene.setSceneRect(QRectF(0,0,1500,1500))

        self.player_map = {}  #播放器{play1:[start,end],play2:[start,end]}

        # bgmpath='D:/Q/audio/Music.mp3'
        # url = QUrl.fromLocalFile(bgmpath)
        # content = QtMultimedia.QMediaContent(url)
        # self.player = QtMultimedia.QMediaPlayer()
        # self.player.setMedia(content)
        # duration = self.player.duration()
        # print(duration)

    # def _auto_bgm_dir(self):
    #     """
    #     自动获取当前bgm的合适索引
    #     :return:
    #     """
    #     bmg_path=os.path.join(self.audioClips_path,'bgm')
    #     bgm_dirs=os.listdir(bmg_path)
    #     max_num=0
    #     if bgm_dirs:
    #         int_bgm_dirs=[int(d) for d in bgm_dirs]
    #         max_num=max(int_bgm_dirs)+1
    #     auto_dir=os.path.join(bmg_path,str(max_num))
    #     return auto_dir
        # 计时器
        # self.timer = QBasicTimer()
        # self.timer.start(500,self)

    # def timerEvent(self, *args, **kwargs):
    #     for p in self.player_list:
    #         if p.position()==p.duration():
    #             p.stop()



    #拖入外部文件
    def dragEnterEvent(self, QDragEnterEvent):
        x=QDragEnterEvent.pos().x()
        if x>100:
            things=QDragEnterEvent.mimeData().text()
            if things.endswith(".mp3") or things.endswith('.wav'):#or things.endswith('.fbx')
                print('drag in audio') #https://blog.csdn.net/chengmo123/article/details/93468426
                QDragEnterEvent.accept()
                bgmpath=things.split('file:///')[1]
                dir_path, file_name = os.path.split(bgmpath)
                m_name, m_type = os.path.splitext(file_name)
                # if m_type in ['.mp3', '.MP3', '.wav', '.WAV']:
                # print(m_type)
                print(bgmpath)
                url = QUrl.fromLocalFile(bgmpath)
                content = QtMultimedia.QMediaContent(url)
                # self.player=QtMultimedia.QMediaPlayer()
                # self.player.setMedia(content)
                # duration=self.player.duration()
                # print(duration)
                player=QtMultimedia.QMediaPlayer()
                player.setMedia(content)
                duration=player.duration()

                data={}
                data['type']='audio'
                data['start']=0  #开始时间
                data['duration']=int(duration/1000)   #转成秒数
                data['path']=bgmpath
                data['name']=m_name
                data['scale']=1  #播放倍数
                # data['status']='stop'
                audioItem=AudioItem(player,data,1000,50)
                self.scene.addItem(audioItem)
                audioItem.setPos(self.scene.width()/2-500,self.scene.height()/2-85)

            elif things.endswith(".mp4") or things.endswith('.avi'):#or things.endswith('.fbx')
                print('drag in video') #https://blog.csdn.net/chengmo123/article/details/93468426
                QDragEnterEvent.accept()
                bgmpath=things.split('file:///')[1]
                dir_path, file_name = os.path.split(bgmpath)
                m_name, m_type = os.path.splitext(file_name)
                print(bgmpath)
                vc = cv2.VideoCapture(bgmpath)
                fps = int(vc.get(cv2.CAP_PROP_FPS))
                frames = vc.get(cv2.CAP_PROP_FRAME_COUNT)
                width = vc.get(cv2.CAP_PROP_FRAME_WIDTH)
                height = vc.get(cv2.CAP_PROP_FRAME_HEIGHT)
                data = {}
                data['type'] = 'video'
                data['start'] = 1  # 开始时间
                # data['duration']=int(duration/1000)   #转成秒数
                data['end'] = frames
                data['path'] = bgmpath
                data['name'] = m_name
                data['fps'] = fps
                data['width'] = width
                data['height'] = height
                data['scale'] = 1  # 播放倍数
                videoItem = VideoItem(data, 1000, 50)
                self.scene.addItem(videoItem)
                videoItem.setPos(self.scene.width() / 2 - 500, self.scene.height() / 2 - 85)

    def contextMenuEvent(self, QContextMenuEvent):
        rMenu = QMenu()
        # importVideoAction=QAction(u'导入视频',None)
        # importVideoAction.triggered.connect(self.import_video)
        importVideoAction=QAction(u'导入视频',None)
        importVideoAction.triggered.connect(self._import_video)
        importAudioAction=QAction(u'导入音频',None)
        importAudioAction.triggered.connect(self._import_audio)
        exportAudioAction = QAction(u'导出音频', None)
        exportAudioAction.triggered.connect(self._export_audio)
        volume_menu=QMenu('倍音输出')
        a_3Action = QAction('÷3', None)
        a_3Action.triggered.connect(self._a_3)
        a_2Action=QAction('÷2', None)
        a_2Action.triggered.connect(self._a_2)
        a2Action = QAction('x2', None)
        a2Action.triggered.connect(self._a2)
        a3Action=QAction('x3',None)
        a3Action.triggered.connect(self._a3)
        volume_menu.addAction(a_3Action)
        volume_menu.addAction(a_2Action)
        volume_menu.addAction(a2Action)
        volume_menu.addAction(a3Action)

        video_menu=QMenu('视频倍数')
        v_3Action = QAction('÷3', None)
        v_3Action.triggered.connect(self._v_3)
        v_2Action=QAction('÷2', None)
        v_2Action.triggered.connect(self._v_2)
        v2Action = QAction('x2', None)
        v2Action.triggered.connect(self._v2)
        v3Action=QAction('x3',None)
        v3Action.triggered.connect(self._v3)
        video_menu.addAction(v_3Action)
        video_menu.addAction(v_2Action)
        video_menu.addAction(v2Action)
        video_menu.addAction(v3Action)

        rMenu.addAction(importVideoAction)
        rMenu.addAction(importAudioAction)
        rMenu.addAction(exportAudioAction)
        rMenu.addMenu(volume_menu)
        rMenu.addMenu(video_menu)

        rMenu.exec(QCursor.pos())


    def _import_video(self):
        """
        导入视频
        :return:
        """
        fileName = QFileDialog.getOpenFileName(None, "请选择视频", ".", "(*.mp4)")
        if fileName[0]:
            bgmpath = fileName[0]
            dir_path, file_name = os.path.split(bgmpath)
            m_name, m_type = os.path.splitext(file_name)
            # if m_type in ['.mp3', '.MP3', '.wav', '.WAV']:
                # print(m_type)
            print(bgmpath)
            vc = cv2.VideoCapture(bgmpath)
            fps = int(vc.get(cv2.CAP_PROP_FPS))
            frames = vc.get(cv2.CAP_PROP_FRAME_COUNT)
            width = vc.get(cv2.CAP_PROP_FRAME_WIDTH)
            height = vc.get(cv2.CAP_PROP_FRAME_HEIGHT)
            data={}
            data['type']='video'
            data['start']=1  #开始时间
            # data['duration']=int(duration/1000)   #转成秒数
            data['end']=frames
            data['path']=bgmpath
            data['name']=m_name
            data['fps']=fps
            data['width']=width
            data['height']=height
            data['scale'] = 1  # 播放倍数
            videoItem=VideoItem(data,1000,50)
            self.scene.addItem(videoItem)
            videoItem.setPos(self.scene.width()/2-500,self.scene.height()/2-85)

    def _import_audio(self):
        """
        导入音频
        :return:
        """
        fileName = QFileDialog.getOpenFileName(None, "请选择音频文件", ".", "(*.mp3;*.wav)")
        if fileName[0]:
            bgmpath = fileName[0]
            dir_path, file_name = os.path.split(bgmpath)
            m_name, m_type = os.path.splitext(file_name)
            # print(m_name, m_type)#D:\Q\audio
            if m_type in ['.mp3', '.MP3', '.wav', '.WAV']:
                # print(m_type)
                print(bgmpath)
                url = QUrl.fromLocalFile(bgmpath)
                content = QtMultimedia.QMediaContent(url)
                # self.player=QtMultimedia.QMediaPlayer()
                # self.player.setMedia(content)
                # duration=self.player.duration()
                # print(duration)
                player=QtMultimedia.QMediaPlayer()
                player.setMedia(content)
                duration=player.duration()
                data={}
                data['type']='audio'
                data['start']=0  #开始时间
                data['duration']=int(duration/1000)   #转成秒数
                data['path']=bgmpath
                data['name']=m_name
                data['scale']=1  #播放倍数
                # data['status']='stop'
                audioItem=AudioItem(player,data,1000,50)
                self.scene.addItem(audioItem)
                audioItem.setPos(self.scene.width()/2-500,self.scene.height()/2-85)
                # self.parent.resetSlider(0,data['duration'])

    def _export_audio(self):
        """
        导出音频信息
        :return:
        """
        sitem=self.scene.selectedItems()
        if sitem:
            audio_items=[]
            for i in sitem:
                if isinstance(i,AudioItem):
                    print(i.data)
                    audio_items.append(i)
            if audio_items:
                fileName = QFileDialog.getSaveFileName(None, "选择保存路径", ".", "mp3(*.mp3)")
                if fileName:
                    save_file=fileName[0]
                    for a in audio_items:
                        data=a.data
                        path=data['path']
                        start=data['start']
                        end=data['end'] if 'end' in data.keys() else data['duration']
                        a_clip=AudioFileClip(path)
                        clip=a_clip.subclip(start,end)
                        clip.write_audiofile(save_file)

    def _v_3(self):
        self._quick_video(0.3)

    def _v_2(self):
        self._quick_video(0.5)

    def _v2(self):
        self._quick_video(2)

    def _v3(self):
        self._quick_video(3)

    def _quick_video(self,factor):
        sitem=self.scene.selectedItems()
        if sitem:
            video_items=[]
            for i in sitem:
                if isinstance(i,VideoItem):
                    print(i.data)
                    video_items.append(i)
            if video_items:
                fileName = QFileDialog.getSaveFileName(None, "选择保存路径", ".", "mp4(*.mp4)")
                if fileName:
                    save_file=fileName[0]
                    for v in video_items:
                        data=v.data
                        path=data['path']
                        # start=data['start']
                        # end=data['end'] if 'end' in data.keys() else data['duration']
                        v_clip=VideoFileClip(path)
                        clip=v_clip.fx(vfx.speedx,factor)
                        clip.write_videofile(save_file)

    def _a_3(self):
        self._lower_audio(0.3)

    def _a_2(self):
        self._lower_audio(0.5)

    def _a2(self):
        self._lower_audio(1.5)

    def _a3(self):
        self._lower_audio(2)

    def _lower_audio(self,factor):
        sitem=self.scene.selectedItems()
        if sitem:
            audio_items=[]
            for i in sitem:
                if isinstance(i,AudioItem):
                    print(i.data)
                    audio_items.append(i)
            if audio_items:
                fileName = QFileDialog.getSaveFileName(None, "选择保存路径", ".", "mp3(*.mp3)")
                if fileName:
                    save_file=fileName[0]
                    for a in audio_items:
                        data=a.data
                        path=data['path']
                        start=data['start']
                        end=data['end'] if 'end' in data.keys() else data['duration']
                        a_clip=AudioFileClip(path)
                        clip=a_clip.subclip(start,end)
                        low_clip=volumex(clip,factor)
                        low_clip.write_audiofile(save_file)


    def reset_parent_slider(self,start,duration):
        """
        重置父窗口滑动条的值
        :param start:
        :param duration:
        :return:
        """
        self.parent.resetSlider(start, duration)

    def reset_parent_btn(self,hold,status):
        """
        重置父窗口暂停键的显示
        :param hold:
        :return:
        """
        self.parent.resetBtn(hold,status)


class ClipWindow(QWidget):

    def __init__(self):
        super(ClipWindow, self).__init__()

        self.up_value=0   #上滑道起始秒
        self.down_value=0  #下滑道起始秒
        self.btn_style='''
                          QPushButton{color:black}
                          QPushButton:hover{color:red}
                          QPushButton{background-color:#FFDEAD}
                          QPushButton{border:2px}
                          QPushButton{border-radius:3px}
                          QPushButton{padding:1px 1px}
                        '''
        self.btn_green_style='''
                          QPushButton{color:#228B22}
                          QPushButton:hover{color:red}
                          QPushButton{background-color:#FFDEAD}
                          QPushButton{border:2px}
                          QPushButton{border-radius:3px}
                          QPushButton{padding:1px 1px}
                        '''
        self.setWindowTitle('音视频剪辑')
        icon_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'imgs', 'cgai.png')
        self.icon = QIcon(icon_path)
        self.setWindowIcon(self.icon)
        self.main_layout=QHBoxLayout()
        self.left_layout=QVBoxLayout()
        self.clipGraph=ClipGraphicView(self)
        self.time_line_layout=QVBoxLayout()
        self.up_layout=QHBoxLayout()
        self.up_start_label=QLabel('0')
        self.up_slider=Myslider(Qt.Horizontal)
        self.up_slider.setTickPosition(QSlider.TicksBelow)
        self.up_slider.valueChanged.connect(self._up_value)
        self.up_play_btn=QPushButton('播放')
        self.up_play_btn.setStyleSheet(self.btn_style)
        self.up_play_btn.clicked.connect(self._play_up)
        self.up_end_label=QLabel('x')
        self.up_layout.addWidget(self.up_start_label)
        self.up_layout.addWidget(self.up_slider)
        self.up_layout.addWidget(self.up_end_label)
        self.up_layout.addWidget(self.up_play_btn)
        self.down_layout=QHBoxLayout()
        self.down_start_label=QLabel('0')
        self.down_slider=Myslider(Qt.Horizontal)
        self.down_slider.setTickPosition(QSlider.TicksAbove)
        self.down_slider.valueChanged.connect(self._down_value)
        self.down_play_btn=QPushButton('播放')
        self.down_play_btn.setStyleSheet(self.btn_style)
        self.down_play_btn.clicked.connect(self._play_down)
        self.down_end_label = QLabel('x')
        self.down_layout.addWidget(self.down_start_label)
        self.down_layout.addWidget(self.down_slider)
        self.down_layout.addWidget(self.down_end_label)
        self.down_layout.addWidget(self.down_play_btn)
        self.btn_layout=QHBoxLayout()
        self.btn_layout.setSpacing(35)
        self.btn_layout.setAlignment(Qt.AlignCenter)
        self.pause_btn=QPushButton('暂停')
        self.pause_btn.clicked.connect(self._pause_item)
        self.pause_btn.setStyleSheet(self.btn_style)
        self.stop_btn=QPushButton('停止')
        self.stop_btn.setStyleSheet(self.btn_style)
        self.stop_btn.clicked.connect(self._stop_item)
        self.cut_btn=QPushButton('截取中间段')
        self.cut_btn.clicked.connect(self._clip_item)
        self.cut_btn.setStyleSheet(self.btn_style)
        self.btn_layout.addWidget(self.pause_btn)
        self.btn_layout.addWidget(self.stop_btn)
        self.btn_layout.addWidget(self.cut_btn)
        self.left_layout.addWidget(self.clipGraph)
        self.left_layout.addLayout(self.up_layout)
        self.left_layout.addLayout(self.down_layout)
        self.left_layout.addLayout(self.btn_layout)

        # self.right_layout=QVBoxLayout()
        # self.information_label=QLabel("信息")
        # self.right_layout.addWidget(self.information_label)

        self.main_layout.addLayout(self.left_layout)
        # self.main_layout.addLayout(self.right_layout)
        self.setLayout(self.main_layout)

    def _up_value(self,value):
        self.up_value=value
        self.up_start_label.setText(str(value))

    def _down_value(self,value):
        self.down_value=value
        self.down_start_label.setText(str(value))

    def resetSlider(self,start,duration):
        """
        刷新slider的大小
        :param duration:
        :param start:
        :param end:
        :return:
        """
        end=start+duration
        self.up_slider.setMinimum(start)
        self.up_slider.setMaximum(end)
        self.up_start_label.setText(str(start))
        self.up_end_label.setText(str(end))
        self.down_slider.setMinimum(start)
        self.down_slider.setMaximum(end)
        self.down_start_label.setText(str(start))
        self.down_end_label.setText(str(end))

    def resetBtn(self,hold,status):
        if hold==1 and status=='pause': #表示暂停
            self.pause_btn.setText('继续')
            self.pause_btn.setStyleSheet(self.btn_green_style)
        else:
            self.pause_btn.setText('暂停')
            self.pause_btn.setStyleSheet(self.btn_style)

    def _play_up(self):
        sitem=self.clipGraph.scene.selectedItems()
        if sitem:
            audio_items=[]
            for i in sitem:
                if isinstance(i,AudioItem):
                    audio_items.append(i)
            if audio_items:
                current_item=audio_items[0]
                current_item.play(self.up_value)

    def _play_down(self):
        sitem=self.clipGraph.scene.selectedItems()
        if sitem:
            audio_items=[]
            for i in sitem:
                if isinstance(i,AudioItem):
                    audio_items.append(i)
            if audio_items:
                current_item=audio_items[0]
                current_item.play(self.down_value)

    def _pause_item(self):
        sitem=self.clipGraph.scene.selectedItems()
        if sitem:
            audio_items=[]
            for i in sitem:
                if isinstance(i,AudioItem):
                    audio_items.append(i)
            if audio_items:
                current_item=audio_items[0]
                current_item.pause()

    def _stop_item(self):
        sitem = self.clipGraph.scene.selectedItems()
        if sitem:
            audio_items=[]
            for i in sitem:
                if isinstance(i,AudioItem):
                    audio_items.append(i)
            if audio_items:
                current_item=audio_items[0]
                current_item.stop()

    def _clip_item(self):
        """
        截取音频
        :return:
        """
        sitem = self.clipGraph.scene.selectedItems()
        if sitem:
            audio_items=[]
            for i in sitem:
                if isinstance(i,AudioItem):
                    audio_items.append(i)
            if audio_items:
                try:
                    current_item=audio_items[0]
                    data={}

                    data['type'] = 'audio'
                    data['start'] = self.up_value  # 开始时间
                    data['duration'] = self.down_value-self.up_value+1 # 转成秒数
                    data['end']=self.down_value
                    data['path'] = current_item.data['path']
                    data['name'] = str(self.up_value)+'-'+str(self.down_value)+ current_item.data['name'][0:4]+'...'
                    data['scale'] = 1  # 播放倍数
                    # data['status'] = 'stop'

                    # url = QUrl.fromLocalFile(data['path'])
                    # content = QtMultimedia.QMediaContent(url)
                    # player = QtMultimedia.QMediaPlayer()
                    # player.setMedia(content)

                    clipItem = AudioItem(current_item.player, data, 400, 50)
                    self.clipGraph.scene.addItem(clipItem)
                    clipItem.setPos(self.clipGraph.scene.width() / 2 - 200, self.scene.clipGraph.scene.height() / 2 - 85)
                except Exception as _clip_item_ERR:
                    print(str(_clip_item_ERR))


if __name__ == '__main__':
    app=QApplication(sys.argv)
    c=ClipWindow()
    c.show()
    sys.exit(app.exec_())